import 'package:flutter/material.dart';

import 'package:top_foundation/utils/util.dart';

import 'index.dart';
import 'widgets/widgets.dart';

class DatePickerPage extends StatefulWidget {
  const DatePickerPage({
    Key? key,
    required this.result,
    this.minDate,
    this.maxDate,
    this.isAm = true,
    this.current,
    this.type = DatePickerType.ymdapm,
    this.isLoop = true,
  }) : super(key: key);
  final DatePickerResult result;

  final DateTime? minDate;
  final DateTime? maxDate;
  final bool isAm;
  final DateTime? current;
  final DatePickerType type;
  final bool isLoop;

  @override
  State<DatePickerPage> createState() => _DatePickerPageState();
}

class _DatePickerPageState extends State<DatePickerPage> {
  late DatePickerController controller;
  late DatePickerState state;

  @override
  void initState() {
    super.initState();
    final String tag = 'picker-${DateTime.now()}';
    controller = Get.put(DatePickerController(), tag: tag);
    state = controller.state;
    Get.log('日历hash---${controller.hashCode}');
    state.result = widget.result;
    state.initData(
      minDate: widget.minDate,
      maxDate: widget.maxDate,
      type: widget.type,
      curr: widget.current,
    );
    controller.initData();
  }

  @override
  void didUpdateWidget(DatePickerPage oldWidget) {
    super.didUpdateWidget(oldWidget);
    state.initData(
      minDate: widget.minDate,
      maxDate: widget.maxDate,
      type: widget.type,
      curr: widget.current,
    );
    controller.initData();
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<DatePickerController>(
      init: controller,
      builder: (_) {
        var state = controller.state;
        var type = state.type;
        return Column(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            Expanded(
              child: GestureDetector(
                onTap: controller.back,
                behavior: HitTestBehavior.opaque,
              ),
            ),
            Container(
              color: Colors.white,
              child: SafeArea(
                top: false,
                child: Column(
                  children: [
                    Container(
                      decoration: const BoxDecoration(
                        border: Border(
                          bottom: BorderSide(
                            color: Color(0xffcdcdcd),
                            width: 0.5,
                          ),
                        ),
                      ),
                      height: 44.r,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          TextButton(
                              onPressed: controller.actionBack,
                              child: Text(
                                '取消',
                                style: TextStyle(
                                  color: const Color(0xff666666),
                                  fontSize: 15.sp,
                                ),
                              )),
                          TextButton(
                              onPressed: controller.actionSure,
                              child: Text(
                                '确定',
                                style: TextStyle(
                                  color: const Color(0xff333333),
                                  fontSize: 15.sp,
                                ),
                              )),
                        ],
                      ),
                    ),
                    SizedBox(
                        height: 300.h,
                        child: Stack(
                          children: [
                            IgnorePointer(
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Expanded(
                                    child: Container(
                                      decoration: BoxDecoration(
                                        gradient: LinearGradient(
                                          begin: Alignment.topCenter,
                                          end: Alignment.bottomCenter,
                                          colors: [
                                            Colors.white,
                                            Colors.white.withOpacity(0.7),
                                          ],
                                        ),
                                      ),
                                    ),
                                  ),
                                  Container(
                                    height: 50.h,
                                    decoration: BoxDecoration(
                                      color: Colors.grey.withOpacity(0.15),
                                      borderRadius: const BorderRadius.all(
                                          Radius.circular(4)),
                                    ),
                                  ),
                                  Expanded(
                                    child: Container(
                                      decoration: BoxDecoration(
                                        gradient: LinearGradient(
                                          begin: Alignment.topCenter,
                                          end: Alignment.bottomCenter,
                                          colors: [
                                            Colors.white.withOpacity(0.7),
                                            Colors.white,
                                          ],
                                        ),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                              children: [
                                GetBuilder<DatePickerController>(
                                  id: 'year',
                                  builder: (controller) {
                                    return _list(
                                      state.minDate?.year ?? 0,
                                      state.maxDate?.year ?? 0,
                                      state.year,
                                      intCount: 4,
                                      valueChanged: (p0) {
                                        state.year = int.parse(p0);
                                        if (state.year == state.curr!.year &&
                                            state.maxDate?.year ==
                                                state.curr!.year) {
                                          if (state.month > state.curr!.month) {
                                            state.month = state.curr!.month;
                                          }
                                        }
                                        controller.update([
                                          'year',
                                          'quarter',
                                          'month',
                                          'day'
                                        ]);
                                      },
                                    );
                                  },
                                ),
                                if (type == DatePickerType.quarter)
                                  GetBuilder<DatePickerController>(
                                    id: 'quarter',
                                    builder: (controller) {
                                      return _quarter(
                                        controller.getMinQuarter(),
                                        controller.getMaxQuarter(),
                                        state.quarter,
                                        valueChanged: (p0) {
                                          state.quarter = p0 + 1;
                                          state.month = DateTimeEx.quarterMonth(
                                              state.quarter);
                                          controller.update(['quarter']);
                                        },
                                      );
                                    },
                                  )
                                else if (type != DatePickerType.y) ...[
                                  GetBuilder<DatePickerController>(
                                    id: 'month',
                                    builder: (controller) {
                                      return _list(
                                        controller.getMinMonth(),
                                        controller.getMaxMonth(),
                                        state.month,
                                        valueChanged: (p0) {
                                          state.month = int.parse(p0);
                                          controller.update(['month', 'day']);
                                        },
                                      );
                                    },
                                  ),
                                  if (type != DatePickerType.ym)
                                    GetBuilder<DatePickerController>(
                                      id: 'day',
                                      builder: (controller) {
                                        return _list(
                                          controller.getMinDay(),
                                          controller.getMaxDay(),
                                          state.day,
                                          valueChanged: (p0) {
                                            state.day = int.parse(p0);
                                            controller.update(['day']);
                                          },
                                        );
                                      },
                                    ),
                                ],
                                if (type == DatePickerType.ymdapm)
                                  GetBuilder<DatePickerController>(
                                    id: 'apm',
                                    builder: (controller) {
                                      var list = const ['上午', '下午'];
                                      return SizedBox(
                                        width: 60.r,
                                        height: 300.h,
                                        child: DateWheelView(
                                          list: list,
                                          value: list[state.apm],
                                          isLoop: false,
                                          valueChanged: (p0) {
                                            state.apm = list.indexOf(p0);
                                            controller.update(['apm']);
                                          },
                                        ),
                                      );
                                    },
                                  ),
                                if (type == DatePickerType.ymdhm ||
                                    type == DatePickerType.meeting)
                                  GetBuilder<DatePickerController>(
                                    id: 'hour',
                                    builder: (controller) {
                                      return _list(
                                        controller.getMinHour(),
                                        controller.getMaxHour(),
                                        state.hour,
                                        valueChanged: (p0) {
                                          state.hour = int.parse(p0);
                                          controller.update(['hour']);
                                        },
                                      );
                                    },
                                  ),
                                if (type == DatePickerType.ymdhm ||
                                    type == DatePickerType.meeting)
                                  GetBuilder<DatePickerController>(
                                    id: 'minute',
                                    builder: (controller) {
                                      return _list(
                                        controller.getMinMinute(),
                                        controller.getMaxMinute(),
                                        state.minute,
                                        list: controller.getMeetingData(),
                                        valueChanged: (p0) {
                                          state.minute = int.parse(p0);
                                          controller.update(['minute']);
                                        },
                                      );
                                    },
                                  ),
                              ],
                            ),
                          ],
                        )),
                  ],
                ),
              ),
            ),
          ],
        );
      },
    );
  }

  Widget _list(
    int start,
    int end,
    int curr, {
    int intCount = 2,
    List<int>? list,
    Function(String)? valueChanged,
  }) {
    var data = list?.map((e) => e.toIntString(intCount)).toList() ??
        List.generate(end - start + 1,
            (index) => (start + index).toIntString(intCount)).toList();
    var value = curr.toIntString(intCount);
    return SizedBox(
      width: 60.r,
      height: 300.h,
      child: DateWheelView(
        value: value,
        list: data,
        valueChanged: valueChanged,
        isLoop: widget.isLoop,
      ),
    );
  }

  Widget _quarter(
    int start,
    int end,
    int curr, {
    required Function(int) valueChanged,
  }) {
    List<String> titles = ['第一季度', '第二季度', '第三季度', '第四季度'];
    var data = titles.sublist(start - 1, end);

    var value = titles[curr - 1];
    return SizedBox(
      width: 90.r,
      height: 300.h,
      child: DateWheelView(
        value: value,
        list: data,
        valueChanged: (t) => valueChanged(titles.indexOf(t)),
        isLoop: widget.isLoop,
      ),
    );
  }
}
